﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WeChatParking.Entity;

namespace WeChatParking.Web.UrlAuthorize
{
    /// <summary>
    /// URL 权限控制
    /// </summary>
    public class UrlAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// Rewrite OnAuthorization
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            int UserID, EnterprisesID;
            try
            {
                string uid = filterContext.HttpContext.Session["UserID"].ToString();
                if (uid == null)
                {
                    //filterContext.HttpContext.Response.Write("请先登陆。");
                    filterContext.HttpContext.Response.Redirect("/Admin/Login");
                    filterContext.HttpContext.Response.End();
                }
                 UserID = int.Parse(uid);
                 EnterprisesID = int.Parse(filterContext.HttpContext.Session["EnterpriseID"].ToString());
            }
            catch (Exception)
            {
                filterContext.HttpContext.Response.Redirect("/Admin/Login");
                filterContext.HttpContext.Response.End();
                throw new HttpException(403, "无权限操作");
            }
            //Get permission list
            List<Permission> pItems = AccountHelper.GetPermissionItems();
            //Get current page permission ID,if items is null,the page you what to access has not been configed.
            var item = pItems.FirstOrDefault(c => c.Route == filterContext.HttpContext.Request.Path);
            if (item != null)
            {
                int[] permissions = AccountHelper.GetUserPermission(UserID, EnterprisesID);
                if (permissions == null)
                {
                    filterContext.HttpContext.Response.Redirect("/Admin/Unauthenticated");
                    filterContext.HttpContext.Response.End();
                    throw new HttpException(403, "无权限操作");
                }
                if (Array.IndexOf<Int32>(permissions, item.ID) == -1)
                {
                    //have not permission  
                    filterContext.HttpContext.Response.Redirect("/Admin/Unauthenticated");
                    filterContext.HttpContext.Response.End();

                    throw new HttpException(403, "无权限操作");
                }
            }
            else
            {
                //the page you what to access has not been configed.
                //filterContext.HttpContext.Response.Write("您想要访问的页面尚未被配置权限。");
                filterContext.HttpContext.Response.Redirect("/Admin/Unauthenticated");
                filterContext.HttpContext.Response.End();
                throw new HttpException(403, "无权限操作");
            }
        }
    }
}